import sys,os
from jili.tool import get_name
import zipfile
from tqdm import tqdm
from pathlib import Path
def get_run_file():
    return sys.argv[0]
def get_run_filename():
    file=get_run_file()
    name=os.path.basename(file)
    return name
def get_run_filename_name(level=0):
    file=get_run_file()
    if level>0:
        n=level+1
        names=file.split(os.path.sep)
        name="_".join(names[-n:])
    else:
        name = os.path.basename(file)
    name=name.split(".")
    name=".".join(name[:-1])
    name=get_name(name,"_")
    return name
def get_run_filepath():
    file=get_run_file()
    name=os.path.dirname(file)
    return name
def compress_file_to_zip(pkl_path, output_path=None, delete_original=False):
    """将pkl文件压缩为ZIP格式"""
    if output_path is None:
        output_path = os.path.splitext(pkl_path)[0] + '.zip'

    with zipfile.ZipFile(output_path, 'w', compression=zipfile.ZIP_LZMA) as zipf:
        zipf.write(pkl_path, arcname=os.path.basename(pkl_path))

    if delete_original:
        os.remove(pkl_path)
    return output_path


def extract_zip(zip_path, extract_path=None, password=None):
    """
    解压ZIP文件

    Args:
        zip_path: ZIP文件路径
        extract_path: 解压目标路径，默认为ZIP文件同级目录下的同名文件夹
        password: ZIP文件密码
    """
    # 检查ZIP文件是否存在
    if not os.path.exists(zip_path):
        raise FileNotFoundError(f"ZIP文件不存在: {zip_path}")

    # 处理目标路径
    if extract_path is None:
        extract_path = os.path.splitext(zip_path)[0]

    # 创建目标目录
    Path(extract_path).mkdir(parents=True, exist_ok=True)

    # 打开ZIP文件
    with zipfile.ZipFile(zip_path, 'r') as zip_ref:
        # 获取所有文件信息
        file_list = zip_ref.infolist()

        # 处理密码
        if password:
            zip_ref.setpassword(password.encode('utf-8'))

        # 解压文件并显示进度
        for file in tqdm(file_list, desc="解压进度"):
            try:
                # 处理中文文件名
                try:
                    filename = file.filename.encode('cp437').decode('gbk')
                except:
                    filename = file.filename

                # 构建完整路径
                file_path = os.path.join(extract_path, filename)

                # 创建目录
                if file.is_dir():
                    Path(file_path).mkdir(parents=True, exist_ok=True)
                else:
                    # 创建父目录
                    os.makedirs(os.path.dirname(file_path), exist_ok=True)
                    # 解压文件
                    with zip_ref.open(file) as src, open(file_path, 'wb') as dst:
                        dst.write(src.read())

            except Exception as e:
                print(f"解压 {filename} 时出错: {e}")